// SPDX-FileCopyrightText: 2024 CitruS Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

package com.fanwj.citrus.features.input

import android.view.InputDevice
import com.fanwj.citrus.CitrusApplication
import com.fanwj.citrus.R
import com.fanwj.citrus.aidl.IFrontend.KeyCode.*
import com.fanwj.citrus.utils.InputHandler.getGUID

val keycodeArray = intArrayOf(
    KEYCODE_DPAD_UP,       KEYCODE_DPAD_DOWN,     KEYCODE_DPAD_LEFT,    KEYCODE_DPAD_RIGHT,
    KEYCODE_BUTTON_A,      KEYCODE_BUTTON_B,      KEYCODE_BUTTON_X,     KEYCODE_BUTTON_Y,
    KEYCODE_BUTTON_L1,     KEYCODE_BUTTON_R1,     KEYCODE_BUTTON_L2,    KEYCODE_BUTTON_R2,
    KEYCODE_BUTTON_THUMBL, KEYCODE_BUTTON_THUMBR, KEYCODE_BUTTON_START, KEYCODE_BUTTON_SELECT,
)

interface CitrusInputDevice {
    fun getName(): String

    fun getGUID(): String

    fun getPort(): Int

    fun getAxes(): IntArray = IntArray(0)

    fun getKeys(): IntArray = IntArray(0)
}

class CitrusPhysicalDevice(
    private val device: InputDevice,
    private val port: Int
) : CitrusInputDevice {

    override fun getName(): String {
        return device.name
    }

    override fun getGUID(): String {
        return device.getGUID()
    }

    override fun getPort(): Int {
        return port
    }

    override fun getAxes(): IntArray = device.motionRanges.map { it.axis }.toIntArray()

    override fun getKeys(): IntArray {
        val availableKeys = mutableSetOf<Int>()
        val hasKeys = device.hasKeys(*keycodeArray)
        for (i in 0 until keycodeArray.size) {
            if (hasKeys[i]) {
                availableKeys.add(keycodeArray[i])
            }
        }
        return availableKeys.toIntArray()
    }
}

class CitrusInputOverlayDevice(
    private val port: Int
) : CitrusInputDevice {

    override fun getName(): String {
        return CitrusApplication.appContext.getString(R.string.input_overlay)
    }

    override fun getGUID(): String {
        return "00000000000000000000000000000000"
    }

    override fun getPort(): Int {
        return port
    }
}
